package com.stu.thread.demo.thread_alternate_print;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class 交替打印2 {


    public static void main(String[] args) {
        Printer2 printer2 = new Printer2();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                printer2.printA();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                printer2.printB();
            }

        }).start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                printer2.printC();
            }

        }).start();
    }
}


class Printer2 {

    private Lock lock = new ReentrantLock();

    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();


    public void printA(){
        lock.lock();
        try {
            for (int i = 0; i< 1;i++) {
               System.out.print("A");
               conditionB.signal();
                try {
                    conditionA.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            conditionB.signal();
        }finally {
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();
        try {
            for (int i = 0; i< 1;i++) {
                System.out.print("B");
                conditionC.signal();
                try {
                    conditionB.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            conditionC.signal();
        }finally {
            lock.unlock();
        }
    }

    public void printC(){
        lock.lock();
        try {
            for (int i = 0; i< 1;i++) {
                System.out.print("C");
                conditionA.signal();
                try {
                    conditionC.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            conditionA.signal();
        }finally {
            lock.unlock();
        }
    }


}